package onlineslideshow.ftp;

import com.zehon.FileTransferStatus;
import com.zehon.exception.FileTransferException;
import com.zehon.ftp.FTPClient;
import java.io.File;
import java.util.ArrayList;

/**
 *
 * @author alex.nebel
 */
public class ftpTransaction {

    private FTPClient ftp;
    private ArrayList<File> files;
    private boolean connected;
    private String remoteFolder, localFolder;
    private boolean isFolder;

    public ftpTransaction(){
        files = new ArrayList<File>();
        connected = false;
        isFolder = false;
        remoteFolder = "./";
        localFolder = "";
    }

    public boolean connect(String host, int port, String user, String pass){
        ftp = null;
        try{
            ftp = new FTPClient(host, port, user, pass);
            connected = true;
            return true;
        }catch(Exception ex){
            connected = false;
            return false;
        }
    }

    public void setFolder(boolean value){
        this.isFolder = value;
    }

    public void setLocalFolder(String folder){
        this.localFolder = folder;
    }

    public void setRemoteFolder(String folder){
        this.remoteFolder = folder;
    }

    public void addFile(File file){
        files.add(file);
    }

    public void removeFile(File file){
        files.remove(file);
    }

    public boolean containsFile(File file){
        return files.contains(file);
    }

    public File[] getFiles(){
        return files.toArray(new File[0]);
    }

    public void start() throws FileTransferException{
        if(!connected){
            throw new FileTransferException("not connected");
        }
        ftpTransferProgress progress = new ftpTransferProgress();
        if(isFolder){
            ftp.sendFolderCreate(localFolder, remoteFolder, progress);
        }else {
            if(!ftp.folderExists(remoteFolder)) {
                ftp.createFolder(remoteFolder, "./");
            }
            for (File file : files) {
                try {
                    progress.transferStart(file.getName());
                    int status = ftp.sendFile(file, remoteFolder);
                    if(status != FileTransferStatus.SUCCESS){
                        progress.transferError(file.getName(), new FileTransferException("status not success"));
                    }
                    progress.transferComplete(file.getName());
                } catch (FileTransferException ftpex) {
                    progress.transferError(file.getName(), ftpex);
                }
            }
        }
    }

    public void rollback(){
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
